package com.dhl.single;

/**
 * @title: 懒汉式线程不安全
 * @Author danghailiang
 * @Date: 2022/7/26 20:39
 * @Version 1.0
 */
public class 懒汉式线程不安全 {
    public static void main(String[] args) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                LazySingle instance1 = null;
                try {
                    instance1 = LazySingle.getInstance();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(instance1);
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                LazySingle instance = null;
                try {
                    instance = LazySingle.getInstance();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(instance);
            }
        }).start();
    }

}
class LazySingle{
    /**
     * 构造器私有化
     */
    private LazySingle() {

    }
    /**
     * 创建静态变量
     */
    private static LazySingle instance;
    /**
     * 返回对象
     */
    public static LazySingle getInstance() throws InterruptedException {
        if(instance == null ){
            // 多线程情况下，可能会有多个请求同时进入该方法，迫使单例失效
            Thread.sleep(2000);
            instance = new LazySingle();
        }
        return instance;
    }
}
